package user_service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"peilian-api/utils/encrypt"
	"peilian-api/utils/tools"
	"time"

	"github.com/gin-gonic/gin"
)

type RdService struct{}

type RdReq struct {
	Sno  string `json:"sno"`
	Sign string `json:"sign"`
}

type BdResp struct {
	Xm     string `json:"xm"`
	Xh     string `json:"xh"`
	Xb     string `json:"xb"`
	Xbdm   string `json:"xb_dm"`
	Xlcc   string `json:"xlcc"`
	Xlccdm string `json:"xlcc_dm"`
	Yxsh   string `json:"yxsh"`
	Yxshdm string `json:"yxsh_dm"`
	Lqzy   string `json:"lqzy"`
	Rxnx   string `json:"rxnx"`
}

var RdUrl = "https://career.ruc.edu.cn/open/api/v1/students"

// 查询人大的学生的详细数据
func (bd *RdService) FetchInfo(ctx *gin.Context, sno string) (string, error) {
	client := &http.Client{}
	key := fmt.Sprintf("key=%s&requestTime=%s&sno=%s", "MIf#H7!dQl%BlPsh", time.Now().Format("200601021504"), sno)
	data := RdReq{Sno: sno, Sign: encrypt.Sm3(key)}
	s, _ := json.Marshal(data)

	request, err := http.NewRequest("POST", RdUrl, bytes.NewReader(s))
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		return "", err
	}
	resp, err := client.Do(request)
	if err != nil {
		return "", err
	}
	if resp != nil {
		defer resp.Body.Close()
	}

	res := make(map[string]interface{})
	err = tools.ReadResponseBodyCtx(ctx, resp, &res)
	if err != nil {
		return "", err
	}

	b, _ := json.Marshal(res["data"])
	return string(b), nil
}
